import { addUser, apiInterceptors, getUserPermissionList,setUserPermission,getAllUserPermissionList } from '@/client/api';
import { useRequest } from 'ahooks';
import { App, Form, Input, Modal, Spin , Select } from 'antd';
import React, { useMemo , useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import styles from './styles.module.css';

interface ShareRoleProps {
  open: boolean;
  onCancel: () => void;
  refresh?: () => Promise<void>;
}

const ShareRole: React.FC<ShareRoleProps> = ({ 
  open, 
  onCancel, 
  refresh 
}) => {
  const { t } = useTranslation();
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<any>([]);
  const userInfo = JSON.parse(localStorage.getItem('edit_user_info') || '{}');

  const formItems = useMemo(() => [
    {
      name: 'login_name',
      label: t('user_name'),
      rules: [{ required: true, message: t('user_name_required')}],
      required:true,
    },
    {
      name: 'nick_name',
      label: t('user_nickname'),
      rules: [{required: true, message: t('user_nickname_required')},],
      required:true,
    },
  ], [t]);

  const { run: setPermission, loading: isSubmitting } = useRequest(
    async (params: any) => {
      const [error] = await apiInterceptors(setUserPermission({user_id:userInfo.id,permissions_ids:params.user_permission}));
      if (error) throw error;
      return params;
    },
    {
      manual: true,
      onSuccess: async (data) => {
        message.success(t('update_success'));
        await refresh?.();
        onCancel();
      },
      onError: () => {
        message.error(t('update_failed'));
      },
    }
  );
  
  const { run: initData } = useRequest(
    async () => {
      return await apiInterceptors(getUserPermissionList({user_id:userInfo.id}));
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res[2] && res[2].success && Array.isArray(res[2].data)) {
          const newUserInfo = {
            ...userInfo,
            user_permission: res[2].data.map((item:any)=>item.id),
          };
          localStorage.setItem('edit_user_info', JSON.stringify(newUserInfo));
          form.setFieldsValue({ user_permission: newUserInfo.user_permission }); 
          return
        }
      },
    },
  );

  const { run: getAllList } = useRequest(
    async () => {
      return await apiInterceptors(getAllUserPermissionList({}));
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res[2] && res[2].success && Array.isArray(res[2].data)) {
          return setDataSource(res[2].data)
        }
      },
    },
  );

  useEffect(() => {
    initData();
    getAllList();
  }, []);

  return (
    <Modal
      className={styles['modal-container']}
      title={t('assign_permissions')}
      width={800}
      open={open}
      okButtonProps={{ disabled: isSubmitting }}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          await setPermission(values);
        } catch (error) {
          console.error('Submission error:', error);
        }
      }}
      onCancel={onCancel}
      centered
    >
      <Spin spinning={isSubmitting}>
        <Form form={form} initialValues={userInfo} labelAlign="right" className='w-4/5'>
          {formItems.map(({ name, label, rules }) => (
            <Form.Item required labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} key={name} name={name} label={label} rules={rules}>
              <Input maxLength={30} disabled placeholder={label} autoComplete="off" />
            </Form.Item>
          ))}
          <Form.Item
            labelCol={{ span: 8 }} 
            wrapperCol={{ span: 16 }} 
            label={`${t('user_permission')}：`}
            name='user_permission'
            required
            rules={[{ required: true, message: t('user_permission_required') }]}
          >
            <Select mode="multiple" placeholder={t('user_permission_required')}>
              {dataSource.map((node:any) => (
                 <Select.Option value={node.id}>{node.name}</Select.Option>
              ))}
             
            </Select>
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};

export default ShareRole;